package com.szy.news;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.szy.news.model.Parameter;
import com.szy.news.service.SyncHttp;

/**
 *@author coolszy
 *@date 2012-2-7
 *@blog http://blog.92coding.com
 * 
 */
public class NewsDetailsActivity extends Activity implements OnGestureListener, OnDoubleTapListener
{
	private ViewFlipper viewFlipper;
	//private GestureDetector mGestureDetector;
	private float startX;
	private int position = 0;
	private LayoutInflater inflater;
	private ArrayList<HashMap<String, Object>> newsList;
	private TextView newsBody;
	private Button previousbutton;
	private Button nextbutton;
	private EditText replyEditText;
	
	private LinearLayout replyEdittextLayout;
	private LinearLayout replyImgLayout;

	private int nid = 0;

	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detailsview);
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		// 设置标题栏名称
		String categoryName = bundle.getString("categoryName");
		TextView titleBarTitle = (TextView) findViewById(R.id.TitleBarTitle);
		titleBarTitle.setText(categoryName);

		Serializable serializable = bundle.getSerializable("newsList");
		newsList = (ArrayList<HashMap<String, Object>>) serializable;
		viewFlipper = (ViewFlipper) findViewById(R.id.viewflipper_data);
		inflater = getLayoutInflater();

		// 获取点击的位置
		position = intent.getIntExtra("position", 1);
		HashMap<String, Object> hashMap = newsList.get(position);
		View wrapperNewsDetailView = inflater.inflate(R.layout.common_info_item_view, null);
		// 新闻标题
		TextView newsTitleText = (TextView) wrapperNewsDetailView.findViewById(R.id.NewsTitleText);
		newsTitleText.setText(hashMap.get("title").toString());
		// 发布时间和出处
		TextView newsTimeAndSource = (TextView) wrapperNewsDetailView.findViewById(R.id.NewsTimeAndSource);
		newsTimeAndSource.setText(hashMap.get("ptime").toString() + "    " + hashMap.get("source").toString());
		// 新闻编号
		nid = (Integer) hashMap.get("nid");
		// 新闻内容
		newsBody = (TextView) wrapperNewsDetailView.findViewById(R.id.newsDetails);
		newsBody.post(new GetNewsBody());
		//回帖数
		Button showComments = (Button)findViewById(R.id.show_comments_back_original); 
		showComments.setText(hashMap.get("commentcount")+"跟帖");
		showComments.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(NewsDetailsActivity.this,CommentsActivity.class);
				intent.putExtra("nid", nid);
				startActivity(intent);
			}
		});
		//mGestureDetector = new GestureDetector(this, this);
		viewFlipper.addView(wrapperNewsDetailView);

		newsBody.setOnTouchListener(new NewsBodyOnTouchListener());

		previousbutton = (Button) findViewById(R.id.previousbutton);
		previousbutton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				showPrevious();
				updateView();
			}
		});
		nextbutton = (Button) findViewById(R.id.nextbutton);
		nextbutton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				showNext();
				updateView();
			}
		});
		updateView();
		
		//跟帖布局
		replyEdittextLayout = (LinearLayout)findViewById(R.id.reply_edittext_layout);
		replyImgLayout = (LinearLayout)findViewById(R.id.reply_img_layout);
		replyEditText = (EditText)findViewById(R.id.reply_edittext);
		ImageButton replyImgButton =(ImageButton)findViewById(R.id.reply_img_button);
		replyImgButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				replyEdittextLayout.setVisibility(View.VISIBLE);
				replyImgLayout.setVisibility(View.GONE);
				replyEditText.requestFocus();
				InputMethodManager m = (InputMethodManager) replyEditText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
				m.toggleSoftInput(0, InputMethodManager.SHOW_IMPLICIT);

			}
		});
		Button replyButton = (Button)findViewById(R.id.reply_button);
		replyButton.setOnClickListener(new PostCommentOnClickListener());
	}

	/**
	 * 处理用户滑屏事件
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		return false;
	}

	@Override
	public boolean onDown(MotionEvent arg0)
	{
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
	{
		System.out.println("onFling");
		// if (e1.getX() - e2.getX() > 120)
		// {
		// this.viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
		// R.anim.push_left_in));
		// this.viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
		// R.anim.push_left_out));
		// this.viewFlipper.addView(addTextByText("文本框"), new
		// LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		// this.viewFlipper.showNext();
		// return true;
		// } else if (e1.getX() - e2.getX() < -120)
		// {
		// this.viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
		// R.anim.push_right_in));
		// this.viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
		// R.anim.push_right_out));
		// this.viewFlipper.showPrevious();
		// return true;
		// }
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e)
	{

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
	{
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e)
	{

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e)
	{
		return false;
	}

	@Override
	public boolean onDoubleTap(MotionEvent e)
	{
		return false;
	}

	@Override
	public boolean onDoubleTapEvent(MotionEvent e)
	{
		return false;
	}

	@Override
	public boolean onSingleTapConfirmed(MotionEvent e)
	{
		return false;
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev)
	{
		// 没有这句，listView会卡住，动不了，，无敌有用
		// this.mGestureDetector.onTouchEvent(ev);//在这里先处理下你的手势左右滑动事件
		return super.dispatchTouchEvent(ev);
	}

	private class UpdateViewAsyncTask extends AsyncTask<Integer, Integer, String>
	{
		private View wrapperNewsDetailView;

		public UpdateViewAsyncTask()
		{
			wrapperNewsDetailView = viewFlipper.getCurrentView();
		}

		@Override
		protected void onPreExecute()
		{
			ImageView newslogo = (ImageView) wrapperNewsDetailView.findViewById(R.id.newslogo);
			newslogo.setVisibility(View.VISIBLE);
			ProgressBar progressBarLoadingDetailView = (ProgressBar) wrapperNewsDetailView.findViewById(R.id.progressBarLoadingDetailView);
			progressBarLoadingDetailView.setVisibility(View.VISIBLE);
			super.onPreExecute();
		}

		protected String doInBackground(Integer... index)
		{
			String body = getNewsBody();
			return body;
		}

		protected void onPostExecute(String result)
		{
			newsBody = (TextView) wrapperNewsDetailView.findViewById(R.id.newsDetails);
			newsBody.setText(Html.fromHtml(result));
			newsBody.setOnTouchListener(new NewsBodyOnTouchListener());
			ImageView newslogo = (ImageView) wrapperNewsDetailView.findViewById(R.id.newslogo);
			newslogo.setVisibility(View.GONE);
			ProgressBar progressBarLoadingDetailView = (ProgressBar) wrapperNewsDetailView.findViewById(R.id.progressBarLoadingDetailView);
			progressBarLoadingDetailView.setVisibility(View.GONE);
		}
	}

	private void showNext()
	{
		if (position<newsList.size()-1)
		{
			viewFlipper.setInAnimation(this, R.anim.push_left_in);
			viewFlipper.setOutAnimation(this, R.anim.push_left_out);
			position++;
			if (position < viewFlipper.getChildCount())
			{
				viewFlipper.showNext();
				return;
			}
			if (position < newsList.size())
			{
				HashMap<String, Object> hashMap = newsList.get(position);
				nid = (Integer) hashMap.get("nid");
				View wrapperNewsDetailView = inflater.inflate(R.layout.common_info_item_view, null);
				TextView newsTitleText = (TextView) wrapperNewsDetailView.findViewById(R.id.NewsTitleText);
				newsTitleText.setText(hashMap.get("title").toString());
				TextView newsTimeAndSource = (TextView) wrapperNewsDetailView.findViewById(R.id.NewsTimeAndSource);
				newsTimeAndSource.setText(hashMap.get("ptime").toString() + "    " + hashMap.get("source").toString());
				viewFlipper.addView(wrapperNewsDetailView);
				System.out.println(viewFlipper.getChildCount());
				viewFlipper.showNext();// 显示下一页
				new UpdateViewAsyncTask().execute(position);
			}
		}
		else
		{
			Toast.makeText(this, "没有下篇新闻了", Toast.LENGTH_SHORT).show();
		}
	}

	private void showPrevious()
	{
		if (position>0)
		{
			position--;
			HashMap<String, Object> hashMap = newsList.get(position);
			nid = (Integer) hashMap.get("nid");
			viewFlipper.setInAnimation(this, R.anim.push_right_in);// 定义下一页进来时的动画
			viewFlipper.setOutAnimation(this, R.anim.push_right_out);// 定义当前页出去的动画
			viewFlipper.showPrevious();// 显示上一页
		}
		else
		{
			Toast.makeText(this, "没有上篇新闻了", Toast.LENGTH_SHORT).show();
		}
	}

	private String getNewsBody()
	{
		String retStr = "网络连接失败，请稍后再试";
		SyncHttp syncHttp = new SyncHttp();
		String url = "http://10.0.2.2:8080/web/getNews";
		String params = "nid=" + nid;
		try
		{
			String retString = syncHttp.httpGet(url, params);
			JSONObject jsonObject = new JSONObject(retString);
			int errcode = jsonObject.getInt("errcode");
			if (0 == errcode)
			{
				JSONObject dataObject = jsonObject.getJSONObject("data");
				JSONObject newsObject = dataObject.getJSONObject("news");
				retStr = newsObject.getString("body");
			}

		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return retStr;
	}

	private void updateView()
	{
		previousbutton.setVisibility(View.VISIBLE);
		nextbutton.setVisibility(View.VISIBLE);
		if (position == 0)
		{
			previousbutton.setVisibility(View.INVISIBLE);
		}
		if (position == newsList.size() - 1)
		{
			nextbutton.setVisibility(View.INVISIBLE);
		}

	}

	private class GetNewsBody implements Runnable
	{
		@Override
		public void run()
		{
			String body = getNewsBody();
			newsBody.setText(Html.fromHtml(body));
		}
	}

	
	private class PostCommentOnClickListener implements OnClickListener
	{
		@Override
		public void onClick(View v)
		{
			SyncHttp syncHttp = new SyncHttp();
			String url = "http://10.0.2.2:8080/web/postComment";
			List<Parameter> params = new ArrayList<Parameter>();
			params.add(new Parameter("nid", nid+""));
			params.add(new Parameter("region", "上海市"));
			params.add(new Parameter("content", replyEditText.getText().toString()));
			try
			{
				String retString = syncHttp.httpPost(url, params);
				JSONObject jsonObject = new JSONObject(retString);
				int errcode = jsonObject.getInt("errcode");
				if (0 == errcode)
				{
					Toast.makeText(NewsDetailsActivity.this, "留言发表成功", Toast.LENGTH_SHORT).show();
					replyEdittextLayout.setVisibility(View.GONE);
					replyImgLayout.setVisibility(View.VISIBLE);
					return;
				}
				
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			Toast.makeText(NewsDetailsActivity.this, "留言发表失败", Toast.LENGTH_SHORT).show();
		}
		
	}
	
	private class NewsBodyOnTouchListener implements OnTouchListener
	{
		@Override
		public boolean onTouch(View v, MotionEvent event)
		{
			switch (event.getAction())
			{
			case MotionEvent.ACTION_DOWN:
				startX = event.getX();
				replyEdittextLayout.setVisibility(View.GONE);
				replyImgLayout.setVisibility(View.VISIBLE);
				break;

			case MotionEvent.ACTION_UP:
				if (event.getX() < startX)
				{
					showNext();
					updateView();

				} else if (event.getX() > startX)
				{
					showPrevious();
					updateView();
				}
				break;
			}
			return true;
		}

	}
}
